package com.huwaiwai.nio.demo02;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 聚集（gather）
 * 写入Channel是指在写操作时将多个buffer的数据写入同一个Channel.
 * 因此，Channel 将多个Buffer中的数据聚集（gather）后发送到Channel
 * Created by huweiwei on 2017/4/20.
 */
public class GatheringWrites {

    public static void main(String [] args) throws IOException {
        RandomAccessFile in = new RandomAccessFile("C:\\test\\src\\main\\java\\com\\huwaiwai\\nio\\file\\nio-data.txt", "rw");
        RandomAccessFile out = new RandomAccessFile("C:\\test\\src\\main\\java\\com\\huwaiwai\\nio\\file\\nio-out.txt", "rw");
        FileChannel inChannel = in.getChannel();
        FileChannel outChannel = out.getChannel();

        ByteBuffer hello = ByteBuffer.allocate(5);
        ByteBuffer world = ByteBuffer.allocate(5);

        //将两个buffer插入数组
        ByteBuffer [] buffers = {hello, world};
        //用buffer数组读取，当第一个buffer充满后才会转到第二个buffer
        inChannel.read(buffers);
        hello.compact();
        world.compact();
        //按顺序写出数据
        outChannel.write(buffers);
        in.close();
        out.close();
    }
}
